package com.zhuiyun.project.api.video.mobileVideo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zhuiyun.project.api.collectVideo.entity.CollectVideo;
import com.zhuiyun.project.api.collectVideo.model.CollectVideoModel;
import com.zhuiyun.project.api.collectVideo.service.CollectVideoService;
import com.zhuiyun.project.api.frontuser.entity.FrontUser;
import com.zhuiyun.project.api.frontuser.mapper.FrontUserMapper;
import com.zhuiyun.project.api.video.mobileVideo.entity.*;
import com.zhuiyun.project.api.video.mobileVideo.mapper.*;
import com.zhuiyun.project.api.video.mobileVideo.model.*;
import com.zhuiyun.project.api.video.mobileVideo.service.MobileVideoService;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.BeanUtils;
import com.zhuiyun.project.utils.RedisUtil;
import com.zhuiyun.project.utils.ScrollResult;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName MobileVideoServiceImpl
 * @Description 移动端视频实现类
 * @Author qsh
 * @Date 2024/3/6 8:37
 **/
@Service
@Transactional
public class MobileVideoServiceImpl implements MobileVideoService {
    @Resource
    private MobileVideoMapper mobileVideoMapper;

    @Resource
    private UserVideoCollectMapper userVideoCollectMapper;

    @Resource
    private UserVideoLikeMapper userVideoLikeMapper;

    @Resource
    private FollowWithInterestMapper followWithInterestMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private F_UserMapper f_userMapper;



    /**
    * @Author qsh
    * @Description 查询推荐页视频
    * @Date 2024/3/8 9:36
    * @Return java.util.List<com.zhuiyun.project.api.video.mobileVideo.model.MobileVideoModel>

    */
    @Override
    public PageResult MobileVideoList(PageRequest pageRequest) {
        //设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(mobileVideoMapper.MobileVideoList());
        return pageResult;
    }

    /**
     * @Author qsh
     * @Description 查询关注页视频
     * @Date 2024/3/8 9:36
     * @Return java.util.List<com.zhuiyun.project.api.video.mobileVideo.model.MobileVideoModel>

     */
    @Override
    public PageResult MobileVideoFollow(String redisKey,PageRequest pageRequest) {
        //获取登录用户信息
        Object userObj = RedisUtil.get(redisKey);
        //将登录信息转为FrontUser
        FrontUser frontUser = (FrontUser) userObj;
        //拼接存储登录用户与关注Up的关联关系的主键
        String key = "follows:"+frontUser.getId();
        //获取登录用户关注的UpID
        Set<Object> objSet = RedisUtil.sGet(key);
        //将获取到的UpID集合转为Set<Integer>
        Set<Integer> UpIdsSet = objSet.stream()
                .map(obj -> (Integer) obj) // 将每个 Object 转换为 UserVideoLike
                .collect(Collectors.toSet()); // 将转换后的 UserVideoLike 放入新的 Set<UserVideoLike> 中
        //创建mobileVideoList 存储关注视频
        List<MobileVideoModel> mobileVideoList = new ArrayList<>();
        //将循环得到的upId作为MobileVideoFollow的查找参数查询关注UP发布的视频
        for(Integer upId : UpIdsSet){
           List<MobileVideoModel> mobileVideoModels = mobileVideoMapper.MobileVideoFollow(upId);
           //将mobileVideoModels的视频数据添加到mobileVideoList
           mobileVideoList.addAll(mobileVideoModels);
        }
        //设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(mobileVideoList);
        return pageResult;
    }

    /**
    * @Author qsh
    * @Description 查询点赞视频ID 高亮app点赞图标
    * @Date 2024/3/18 16:16
    * @Return java.util.List<com.zhuiyun.project.api.video.mobileVideo.entity.UserVideoLike>
    * @param redisKey
    */
    @Override
    public List<UserVideoLike> LikeList(String redisKey) {
        //获取登录用户信息
        Object userObj = RedisUtil.get(redisKey);
        //将登录信息转为FrontUser
        FrontUser frontUser = (FrontUser) userObj;

        Example example = new Example(UserVideoLike.class);
        example.createCriteria().andEqualTo("userId",frontUser.getId());
        List<UserVideoLike> userVideoLikeList = userVideoLikeMapper.selectByExample(example);
        return userVideoLikeList;
    }

    /**
    * @Author qsh
    * @Description 查询收藏视频ID 高亮app收藏图标
    * @Date 2024/3/18 16:16
    * @Return java.util.List<com.zhuiyun.project.api.video.mobileVideo.entity.UserVideoLike>
    * @param redisKey
    */
    @Override
    public List<UserVideoCollect> collectList(String redisKey) {
        //获取登录用户信息
        Object userObj = RedisUtil.get(redisKey);
        //将登录信息转为FrontUser
        FrontUser frontUser = (FrontUser) userObj;
        Example example = new Example(UserVideoCollect.class);
        example.createCriteria().andEqualTo("userId",frontUser.getId());
        List<UserVideoCollect> userVideoCollectList = userVideoCollectMapper.selectByExample(example);
        return userVideoCollectList;
    }

    /**
    * @Author qsh
    * @Description 查询用户关注UPId（隐藏app关注图标
    * @Date 2024/3/18 16:58
    * @Return java.util.List<com.zhuiyun.project.api.video.mobileVideo.entity.FollowWithInterest>
    * @param redisKey
    */
    @Override
    public List<FollowWithInterest> followList(String redisKey) {
        //获取登录用户信息
        Object userObj = RedisUtil.get(redisKey);
        //将登录信息转为FrontUser
        FrontUser frontUser = (FrontUser) userObj;
        Example example = new Example(FollowWithInterest.class);
        example.createCriteria().andEqualTo("userOneId",frontUser.getId());
        List<FollowWithInterest> followWithInterests = followWithInterestMapper.selectByExample(example);
        return followWithInterests;
    }

    /**
    * @Author qsh
    * @Description 关注视频发布者
    * @Date 2024/3/14 9:29
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param followWithInterestModel
    */
    @Override
    public CommonResult UserFollow(FollowWithInterestModel followWithInterestModel) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(followWithInterestModel)){
            //创建关注类
            FollowWithInterest followWithInterest = new FollowWithInterest();
            //copy
            BeanUtils.copy(followWithInterestModel, followWithInterest);
            Object userObj = RedisUtil.get(followWithInterestModel.getRedisUserKey());
            FrontUser frontUser = (FrontUser) userObj;
            if (frontUser!=null){
                //将关注id、被关注id保存到关注关联表
                followWithInterest.setUserOneId(frontUser.getId());
                Long l = System.currentTimeMillis();
                followWithInterest.setTs(l);
                followWithInterestMapper.insert(followWithInterest);

                //关注者的关注数加一
                Example example = new Example(FrontUser.class);
                example.createCriteria().andEqualTo("id",frontUser.getId());
                UserInformation userInformation = f_userMapper.selectOneByExample(example);
                userInformation.setFollowWithInterest(userInformation.getFollowWithInterest()+1);
                f_userMapper.updateByExampleSelective(userInformation,example);

                //被关注者的粉丝数加一
                Example example1 = new Example(FrontUser.class);
                example1.createCriteria().andEqualTo("id",followWithInterest.getUserTwoId());
                UserInformation userInformation1 = f_userMapper.selectOneByExample(example1);
                userInformation1.setFans(userInformation1.getFans()+1);
                f_userMapper.updateByExampleSelective(userInformation1,example1);
            }
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else{
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
    * @Author qsh
    * @Description 点赞
    * @Date 2024/3/8 10:26
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param userVideoLikeModel
    */
    @Override
    public CommonResult UserLike(UserVideoLikeModel userVideoLikeModel,Integer idx) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(userVideoLikeModel)){
            UserVideoLike userVideoLike = new UserVideoLike();
            // publishVideoModel 对象拷贝成 video
            BeanUtils.copy(userVideoLikeModel, userVideoLike);
            Object userObj = RedisUtil.get(userVideoLikeModel.getRedisUserKey());
            FrontUser frontUser = (FrontUser) userObj;
                //idx==1时 为用户点赞
                if(idx == 1) {
                    userVideoLike.setUserId(frontUser.getId());
                    Long l = System.currentTimeMillis();
                    userVideoLike.setTs(l);
                    int i = userVideoLikeMapper.insert(userVideoLike);
                    if (i > 0) {
                        return CommonResult.ok(EmErrorCode.SAVE_OK);
                    } else {
                        return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                    }
                }else {
                    Example example = new Example(UserVideoLike.class);
                    example.createCriteria().andEqualTo("videoId",userVideoLike.getVideoId());
                    example.createCriteria().andEqualTo("userId",frontUser.getId());
                    int i = userVideoLikeMapper.deleteByExample(example);
                    if (i > 0) {
                        return CommonResult.ok(EmErrorCode.DELETE_OK);
                    } else {
                        return CommonResult.ok(EmErrorCode.DELETE_ERROR);
                    }
                }
        }else{
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }

    /**
     * @Author qsh
     * @Description 收藏
     * @Date 2024/3/8 10:26
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param userVideoCollectModel
     */
    @Override
    public CommonResult UserFavorites(UserVideoCollectModel userVideoCollectModel, Integer idc) throws CommonException {
        // 验证参数的规范性
        if(ValidatorUtil.ValidationObject(userVideoCollectModel)){
            UserVideoCollect userVideoCollect = new UserVideoCollect();
            // publishVideoModel 对象拷贝成 video
            BeanUtils.copy(userVideoCollectModel, userVideoCollect);
            Object userObj = RedisUtil.get(userVideoCollectModel.getRedisUserKey());
            FrontUser frontUser = (FrontUser) userObj;
            if(idc == 1) {
                userVideoCollect.setUserId(frontUser.getId());
                Long l = System.currentTimeMillis();
                userVideoCollect.setTs(l);
                int i = userVideoCollectMapper.insert(userVideoCollect);
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.SAVE_OK);
                } else {
                    return CommonResult.ok(EmErrorCode.SAVE_ERROR);
                }
            }else {
                userVideoCollect.setUserId(frontUser.getId());
                Example example = new Example(UserVideoCollect.class);
                example.createCriteria().andEqualTo("userId",frontUser.getId());
                example.createCriteria().andEqualTo("videoId",userVideoCollect.getVideoId());
                int i = userVideoCollectMapper.deleteByExample(example);
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.DELETE_OK);
                } else {
                    return CommonResult.error(EmErrorCode.DELETE_ERROR);
                }
            }
        }else{
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }

    /**
    * @Author qsh
    * @Description 持久化点赞数据
    * @Date 2024/3/8 16:55
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param videoIndexing
    */
    @Override
    public CommonResult Likes(MobileVideo mobileVideo,Integer videoIndexing) throws CommonException {
        if(ValidatorUtil.ValidationObject(videoIndexing)){
            Example example = new Example(MobileVideo.class);
            example.createCriteria().andEqualTo("vId",mobileVideo.getVId());
            MobileVideo mVideo = mobileVideoMapper.selectOneByExample(example);
            if (mobileVideo.getDzFlag()==0){
                mVideo.setLikeCounts(mVideo.getLikeCounts() + 1);

            }else {
                mVideo.setLikeCounts(mVideo.getLikeCounts() - 1);
            }
            int i = mobileVideoMapper.updateByExampleSelective(mVideo, example);
            if (i>0){

            }else {
                CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else{
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
    * @Author qsh
    * @Description 持久化收藏数据
    * @Date 2024/3/21 18:58
    * @Return com.zhuiyun.project.common.response.CommonResult
    * @param mobileVideo
* @param videoIndexing
    */
    @Override
    public CommonResult collect(MobileVideo mobileVideo, Integer videoIndexing) throws CommonException {
        if(ValidatorUtil.ValidationObject(videoIndexing)){
            Example example = new Example(MobileVideo.class);
            example.createCriteria().andEqualTo("vId",mobileVideo.getVId());
            MobileVideo mVideo = mobileVideoMapper.selectOneByExample(example);
            if (mobileVideo.getDzFlag()==0){
                mVideo.setCollectCounts(mVideo.getCollectCounts() + 1);
            }else {
                mVideo.setCollectCounts(mVideo.getCollectCounts() - 1);
            }
            int i = mobileVideoMapper.updateByExampleSelective(mVideo, example);
            if (i>0){

            }else {
                CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else{
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }
}
